package com.kly.manager.ai;// 建议dashscope SDK的版本 >= 2.15.0

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
// 智能体应用调用实现流式输出结果

@Component
@Slf4j
public class AIAppManager {

    @Value("${aliYun.ai.apiKey}")
    private String apiKey;

    @Value("${aliYun.ai.appId}")
    private String appId;


    public Flowable<ApplicationResult> streamCall(String prompt) throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey(apiKey)
                // 替换为实际的应用 ID
                .appId(appId)
                .prompt(prompt)
                // 增量输出
                .incrementalOutput(true)
                .build();
        Application application = new Application();
        ApplicationResult result = application.call(param);
        param.setSessionId(result.getOutput().getSessionId());
        // .streamCall（）：流式输出内容
        return application.streamCall(param);
    }
}